package com.topsail.demo.context;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <B>主类名称：</B>JwtUtils<BR>
 * <B>概要说明：</B>Jwt工具类<BR>
 *
 * @author steven.zhoulin
 *
 * @since 2023年7月10日 19:37
 */
public final class JwtUtils {

    private static final Logger log = LoggerFactory.getLogger(JwtUtils.class);

    // 加密秘钥
    private static final String KEY = "123321";

    // Token 存活期，单位分钟
    private static final int LIFETIME_MINUTES = 60 * 24 * 30;

    private static final String issuer = "topsail";
    private static final String audience = "topsail";

    /**
     * 创建 JavaWebToken
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createJwt(Long userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);

        Date expiration = DateUtils.addMinutes(new Date(), LIFETIME_MINUTES);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setIssuer(issuer)
                .setAudience(audience)
                .setClaims(claims)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

    /**
     * Token 续期
     *
     * @param token
     * @return
     */
    public static String refreshJwt(String token) {

        try {
            Map<String, Object> claims = parserJwt(token);
            return Jwts.builder()
                    .setHeaderParam("typ", "JWT")
                    .setIssuer(issuer)
                    .setAudience(audience)
                    .setClaims(claims)
                    .setExpiration(DateUtils.addMinutes(new Date(), LIFETIME_MINUTES))
                    .signWith(SignatureAlgorithm.HS256, KEY)
                    .compact();
        } catch (ExpiredJwtException e) {
            log.error("Token续期发生错误: " + e.getMessage());
            return "";
        }

    }

    /**
     * 解析 JavaWebToken
     *
     * @param token
     * @return
     */
    public static Map<String, Object> parserJwt(String token) {
        try {
            Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
            return jwtClaims;
        } catch (ExpiredJwtException e) {
            throw e;
        } catch (Exception e) {
            // 时间到了就直接报错了
            log.error("json web token verify failed");
            return null;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String token = createJwt(1000L, "steven.zhou");
        System.out.println("token: " + token);
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000 * 70);
            System.out.println(refreshJwt(token));
        }


//        Map<String, Object> map = JwtUtils.parserJwt(jwt);
//        System.out.println("map: " + map);
    }

}
